
from flask import session, g, jsonify, views, request, url_for
from flask_login import current_user, login_required
from flask_restful import Resource, reqparse, fields, marshal_with, marshal
from flask_restful.reqparse import Argument

from app import db
from app.decorators import permission_required
from app.view import CommonResource, parse_args
from . import sys
from app.utils import Node, gen_tree, page2dict
from app.models import User




@login_required
@sys.route('/user/menu', methods=['GET', 'POST'])
def get_user_menu():
    rs = current_user.resources()
    sorted_resources =sorted(rs, key=lambda resource: resource.order or resource.id )
    r = gen_tree(sorted_resources)
    return jsonify(r.dict())




class UserResource(CommonResource):

    def __init__(self):
        super().__init__(User)

    paginate_fields={
        'name': fields.String(attribute='name'),
        'email': fields.String(attribute='email'),
        'username': fields.String(attribute='username')
    }

    post_args = [Argument(name='username', type=str, required=True , help='sfdsf::{error_msg}'),
                 Argument(name='name', type=str, required=True,),
                 Argument(name='email', type=str, required=True , help='{error_msg}'),
                 ]

    put_args = [Argument(name='username', type=str, required=True , help='sfdsf::{error_msg}'),
                 Argument(name='name', type=str, required=True,),
                 Argument(name='email', type=str, required=True , help='{error_msg}'),
                 ]
    pass


    def post_entity_handler(self,entity):
        entity.password = '11111111'



class GroupResource(CommonResource):

    def __init__(self):
        super().__init__(User)

    paginate_fields={
        'name': fields.String(attribute='name'),
    }


    post_args = [Argument(name='username', type=str, required=True , help='sfdsf::{error_msg}'),
                 Argument(name='name', type=str, required=True,),
                 Argument(name='email', type=str, required=True , help='{error_msg}'),
                 ]

    put_args = [Argument(name='username', type=str, required=True , help='sfdsf::{error_msg}'),
                 Argument(name='name', type=str, required=True,),
                 Argument(name='email', type=str, required=True , help='{error_msg}'),
                 ]



    def post_entity_handler(self,entity):
        pass

